﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Parichay.Domain; using Parichay.Domain.Models;
using Parichay.Data.Helper;

namespace Parichay.MVC.Controllers
{
    public class PostController : AuthController
    {
        //
        // GET: /Post/
        Domain.Interface.Data.IMemberPostsRepository _memberPostsRepository;

        public PostController(Domain.Interface.Data.IMemberPostsRepository memberPostsRepository)
        {
            _memberPostsRepository = memberPostsRepository;
        }

        public ActionResult Index()
        {
            IList<Parichay.Domain.MemberPosts> lst = NHibernateHelper.ConvertToListOf<Parichay.Domain.MemberPosts>(NHibernateHelper.Find("select distinct p from MemberPosts as p where p.Sender.Id=? and p.Recipient.Id=? order by p.Createdon desc", new object[] { LoggedInUserKey, LoggedInUserKey }, new NHibernate.Type.IType[] { NHibernate.NHibernateUtil.Int32, NHibernate.NHibernateUtil.Int32 }, false));
            return View(lst);
        }

        [HttpPost]
        public ActionResult CreatePost(int? rUrl, MemberPosts model)
        {
            var result = new JsonResponse();
            if (string.IsNullOrEmpty(model.Text))
            {
                result.isSuccessful = false;
                TempData["message"] = result.errorMessage = "Message cannot be blank.";
            }
            else
            {
                //update the database
                if (IsUserAuthenticated)
                {
                    try
                    {

                        MemberDetails thisUsr = Parichay.Data.Helper.NHibernateHelper.UniqueResult<MemberDetails>(null, "Id", LoggedInUserKey);
                        MemberDetails recipient = ((model.Recipient==null)||(model.Recipient.Id==LoggedInUserKey))?thisUsr:Parichay.Data.Helper.NHibernateHelper.UniqueResult<MemberDetails>(null, "Id", model.Recipient.Id);
                        
                        var msg = new MemberPosts
                        {
                            Text = model.Text.Replace("\r\n", " "),
                            Modifiedon = DateTime.Now.ToUniversalTime(),
                            Createdon = DateTime.Now.ToUniversalTime(),
                            Sender = thisUsr,
                            Recipient = recipient,
                            Type = ((int)model.Type),
                            IsPrivate = false,
                            Source = "parichay",
                        };



                        Parichay.Data.Helper.NHibernateHelper.Save<MemberPosts>(msg);


                        result.Id = msg.Id.ToString();

                        result.isSuccessful = true;
                        TempData["message"] = result.responseText = "Posted Successfully";
                    }
                    catch (Exception excp1)
                    {
                        _logRepository.Log(new Exception("Error Adding Post=>", excp1));
                        result.isSuccessful = false;
                        TempData["message"] = result.errorMessage = "Failed to post. Error: " + excp1.Message;
                    }
                }
                else
                {
                    result.isSuccessful = false;
                    TempData["message"] = result.errorMessage = "You must be logged in to post a message.";
                }
            }
            if (IsJsonRequest())
            { return Json(result); }
            else
            {
                return RedirectToAction("Index", ((Parichay.AppConstants.ReturnContollerHomes)model.rUrl).ToString());
            }
        }

        public ActionResult Reply(int id, int rId, int? rUrl)
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddReply(int id, int rId, int? rUrl, MemberReplies model)
        {
            var result = new JsonResponse();
            if (string.IsNullOrEmpty(model.Text))
            {
                result.isSuccessful = false;
                TempData["message"] = result.errorMessage = "Message cannot be blank.";
            }
            else
            {
                //update the database
                if (IsUserAuthenticated)
                {
                    try
                    {

                        MemberDetails thisUsr = Parichay.Data.Helper.NHibernateHelper.UniqueResult<MemberDetails>(null, "Id", LoggedInUserKey);
                        MemberPosts parent = Parichay.Data.Helper.NHibernateHelper.UniqueResult<MemberPosts>(null, "Id", id);
                        MemberDetails recipient = (rId == LoggedInUserKey) ? thisUsr : parent.Sender;


                        var msg = new MemberReplies
                        {
                            Text = model.Text.Replace("\r\n", " "),
                            Modifiedon = DateTime.Now.ToUniversalTime(),
                            Createdon = DateTime.Now.ToUniversalTime(),
                            Sender = thisUsr,
                            Recipient=recipient,
                            Type = ((int)model.Type),
                            IsPrivate = false,
                            Source = "parichay",
                            Parent = parent
                        };




                        Parichay.Data.Helper.NHibernateHelper.Save<MemberReplies>(msg);

                        //Sending Notify Now
                        if (msg.Sender.Id != msg.Recipient.Id)
                        {
                            try
                            {
                                string msgUrl = "<a href='" + Url.Action("Dtl", "Post", new { id = msg.Parent.Id }) + "' >reply</a>";
                                Alert(msg.Recipient.Id, string.Format("You have received a ({0}) to your post from: {1}", msgUrl, msg.Sender.Givennm));
                            }
                            catch (Exception ex1)
                            {

                                _logRepository.Log(new Exception("Error Adding Reply Alert=>", ex1));
                            }
                        }

                        result.Id = msg.Id.ToString();



                        result.isSuccessful = true;
                        TempData["message"] = result.responseText = "Reply Sent.";
                    }
                    catch (Exception excp1)
                    {
                        _logRepository.Log(new Exception("Error Adding Reply=>", excp1));
                        result.isSuccessful = false;
                        TempData["message"] = result.errorMessage = "Failed to add reply. Error: " + excp1.Message;
                    }
                }
                else
                {
                    result.isSuccessful = false;
                    TempData["message"] = result.errorMessage = "You must be logged in to reply";
                }
            }
            if (IsJsonRequest())
            { return Json(result); }
            else
            {
                if (!rUrl.HasValue)
                {
                    return RedirectToAction("Index");
                }else
                return RedirectToAction("Index", ((Parichay.AppConstants.ReturnContollerHomes)rUrl).ToString());
            }
        }

        [HttpPost]
        public ActionResult Delete(int id, int? rUrl)
        {
            var result = new JsonResponse();

            try
            {
                //delete message from database
                //make sure the user has the right to delete

                //get the message
                MemberPosts lstResults = Data.Helper.NHibernateHelper.UniqueResult<MemberPosts>(null, new string[] { "Id", "Sender.Id" }, new object[] { id, LoggedInUserKey });
                //MemberMessage lstResults = m_PersistenceManager.UniqueResult<MemberMessage>(null,  "Id",id );

                if (lstResults != null)
                {
                    MemberPosts message = lstResults;

                    int childCount = Data.Helper.NHibernateHelper.Count("select m.Id from MemberReplies m where m.Parent.Id=?", id, NHibernate.NHibernateUtil.Int32, false);

                    if (childCount > 0)
                    {
                        result.isSuccessful = false;
                        TempData["message"] = result.errorMessage = "You cannot delete post that have been replied to.";
                    }
                    else
                    {
                        if (message.Type == 2)
                        {
                            ////delete the files
                            //try
                            //{
                            //    AmazonHelper.Delete(message.ImageFilename); //image
                            //    AmazonHelper.Delete(message.ThumbnailFilename); //thumbnail
                            //}
                            //catch (Exception ex)
                            //{
                            //    Utils.Log(ex);
                            //}
                        }

                        Data.Helper.NHibernateHelper.Delete<MemberPosts>(message);
                        result.isSuccessful = true;
                        TempData["message"] = result.errorMessage = "Post deleted.";
                    }
                }
                else
                {
                    result.isSuccessful = false;
                    TempData["message"] = result.errorMessage = "Post already deleted or you don't have permission to delete it.";
                }
            }
            catch (Exception exc)
            {
                result.isSuccessful = false;
                _logRepository.Log(new Exception("Error deleting post. ==> ", exc));
                TempData["message"] = result.errorMessage = "Unexpected error while deleting post.";
            }
            if (IsJsonRequest())
            {
                return Json(result);
            }
            else
            {
                int rUrl2 = rUrl.HasValue ? rUrl.Value : 0;
                return RedirectToAction("Index", ((Parichay.AppConstants.ReturnContollerHomes)rUrl2).ToString());
            }
        }

        public ActionResult Del(int id, int? rUrl)
        {
            return Delete(id, rUrl);
        }

        [HttpPost]
        public ActionResult DeleteReply(int id, int? rUrl)
        {
            var result = new JsonResponse();

            try
            {
                //delete message from database
                //make sure the user has the right to delete

                //get the message
                MemberReplies lstResults = Data.Helper.NHibernateHelper.UniqueResult<MemberReplies>(null, new string[] { "Id", "Sender.Id" }, new object[] { id, LoggedInUserKey });
                //MemberMessage lstResults = m_PersistenceManager.UniqueResult<MemberMessage>(null,  "Id",id );

                if (lstResults != null)
                {
                    MemberReplies message = lstResults;

                        if (message.Type == 2)
                        {
                            ////delete the files
                            //try
                            //{
                            //    AmazonHelper.Delete(message.ImageFilename); //image
                            //    AmazonHelper.Delete(message.ThumbnailFilename); //thumbnail
                            //}
                            //catch (Exception ex)
                            //{
                            //    Utils.Log(ex);
                            //}
                        }

                        Data.Helper.NHibernateHelper.Delete<MemberReplies>(message);
                        result.isSuccessful = true;
                        TempData["message"] = result.errorMessage = "Reply deleted.";

                }
                else
                {
                    result.isSuccessful = false;
                    TempData["message"] = result.errorMessage = "Reply already deleted or you don't have permission to delete it.";
                }
            }
            catch (Exception exc)
            {
                result.isSuccessful = false;
                _logRepository.Log(new Exception("Error deleting reply. ==> ", exc));
                TempData["message"] = result.errorMessage = "Unexpected error while deleting reply.";
            }
            if (IsJsonRequest())
            {
                return Json(result);
            }
            else
            {
                int rUrl2 = rUrl.HasValue ? rUrl.Value : 0;
                return RedirectToAction("Index", ((Parichay.AppConstants.ReturnContollerHomes)rUrl2).ToString());
            }
        }

        public ActionResult DelReply(int id, int? rUrl)
        {
            return DeleteReply(id, rUrl);
        }

        public ActionResult Dtl(int id, int? rUrl)
        {
            MemberPosts model = Data.Helper.NHibernateHelper.UniqueResult<MemberPosts>(null, "Id", id);
            return View(model);
        }

        private IList<Domain.MemberPosts> getPostsByUId(int uId)
        {
            return (_memberPostsRepository.GetMemberPostsByUserId(uId, 10, 0));
        }

        private IList<Domain.MemberPosts> getFriendPostsByUId(int uId)
        {
            return (_memberPostsRepository.GetFriendsMemberPostsByUserId(uId, 10, 0));
        }
    }
}
